package com.example.aqarapp.view.fragment;

import static com.example.aqarapp.view.MainPageActivity.FAMILY_CHANGE;
import static com.example.aqarapp.view.MainPageActivity.curFamilyName;
import static com.example.aqarapp.view.MainPageActivity.curRoomName;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.example.aqarapp.entity.BaseDeviceInfo;
import com.example.aqarapp.entity.BulbInfo;
import com.example.aqarapp.entity.CurtainInfo;
import com.example.aqarapp.entity.DeviceInfo;
import com.example.aqarapp.entity.SocketInfo;
import com.example.aqarapp.view.AverageGapItemDecoration;
import com.example.aqarapp.view.HorizontalItemDecoration;
import com.example.aqarapp.view.adapter.DeviceRecyclerAdapter;
import com.example.aqarapp.view.adapter.QuickPlaceRecyclerAdapter;
import com.example.aqarapp.view.dialog.BulbControlDialog;
import com.example.aqarapp.view.dialog.CurtainControlDialog;
import com.example.aqarapp.view.utils.MessageEvent;
import com.example.aqarapp.viewmodel.FamilyInfoViewModel;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import aqarapp.R;

public class QuickCtlFragment<Public> extends Fragment implements View.OnClickListener {
    private RecyclerView mQuickControlRv;
    private DeviceRecyclerAdapter mDeviceListAdapter;
    private QuickPlaceRecyclerAdapter mQuickPlaceAdapter;
    private ArrayList<String> dataList;
    private ArrayList<String> placeDataList;
    private BulbControlDialog mBulbControlDialog;
    private ImageButton bulbCancelBtn;
    private SmartRefreshLayout smartRefreshLayout;
    private CurtainControlDialog mCurtainControlDialog;
    private ImageButton curtainCancelBtn;
    private RecyclerView mDeviceRv;
    private FamilyInfoViewModel mFamilyInfoViewModel;
    private MutableLiveData<List<String>> mRoomNameInfoLiveData;
    private ArrayList<String> roomList = new ArrayList<>();
    private MutableLiveData<List<DeviceInfo>> mRoomDeviceInfoLivewData;
    private List<DeviceInfo> curRoomDeviceList = new ArrayList<>();


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.layout_quick_refresh_block, null);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initViewModel();
        initQuickControlPlaceView();
        initDeviceRecyclerView();
        initRefreshLayout();
    }

    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    private void initViewModel() {
        mFamilyInfoViewModel = new ViewModelProvider(requireActivity()).get(FamilyInfoViewModel.class);
        mRoomNameInfoLiveData = (MutableLiveData<List<String>>) mFamilyInfoViewModel.getRoomNameInfo();
        mRoomDeviceInfoLivewData = (MutableLiveData<List<DeviceInfo>>) mFamilyInfoViewModel.getDeviceInfo();
        mRoomNameInfoLiveData.observe(getViewLifecycleOwner(), item -> {
            mQuickPlaceAdapter.setList(item); //更新横排room名称
        });
        mRoomDeviceInfoLivewData.observe(getViewLifecycleOwner(), item -> {
            mDeviceListAdapter.setList(item); //更新对应room cardView
        });
    }

    private void initQuickControlPlaceView() {
        mQuickControlRv = getView().findViewById(R.id.quick_control_place_rv);
        mQuickControlRv.setHasFixedSize(true); //设置固定大小
        //TODO 这里的间隔距离需要确定
        HorizontalItemDecoration itemDecoration =
                new HorizontalItemDecoration(25, getContext());
        mQuickControlRv.addItemDecoration(itemDecoration);
        //创建线性布局
        mQuickPlaceAdapter = new QuickPlaceRecyclerAdapter(R.layout.layout_quick_ctl_place_tab); //初始化适配器
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext(), RecyclerView.HORIZONTAL, false);
        mQuickControlRv.setLayoutManager(linearLayoutManager);
        mQuickControlRv.setAdapter(mQuickPlaceAdapter);
        mQuickPlaceAdapter.setEmptyView(R.layout.layout_empty);
        //设置未发现设备时的布局
        mQuickPlaceAdapter.setOnItemClickListener(new OnItemClickListener() {  //卡片的点击事件
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                //选择快捷或其他地点需要显示对应的卡片页面
                mQuickPlaceAdapter.setSelection(position);
                curRoomName = (String) adapter.getItem(position);
                //TODO  "快捷未加上"
//                if (curLocation.equals("快捷")) {
//                    mDeviceListAdapter.setList(allDeviceList);
//                } else {
                //获取对应location的所有设备信息
                mRoomDeviceInfoLivewData.setValue(mFamilyInfoViewModel.getQuickDeviceItem(curRoomName));
//                }
            }
        });
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    private void initRefreshLayout() {
        smartRefreshLayout = getView().findViewById(R.id.quick_refreshLayout);
        smartRefreshLayout.setEnableRefresh(true);//是否启用下拉刷新功能
        smartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                Toast.makeText(getActivity(), "我请求下拉刷新数据", Toast.LENGTH_LONG).show();
                //调用远程接口重新获取所有数据
                mFamilyInfoViewModel.RefreshDeviceList();
                mRoomNameInfoLiveData.setValue(mFamilyInfoViewModel.getRoomNameList(curFamilyName));
                mRoomDeviceInfoLivewData.setValue(mFamilyInfoViewModel.getQuickDeviceItem(curRoomName));
                //mRoomDeviceInfoLivewData.setValue(curRoomDeviceList);
                refreshLayout.finishRefresh(1000);//TODO 这里指定2s结束,后续可能根据数据返回回调通知结束刷新动画
            }
        });
    }

    @Override
    public void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mBulbControlDialog != null) {
            mBulbControlDialog.dismiss();
        }
        if (mCurtainControlDialog != null) {
            mCurtainControlDialog.dismiss();
        }
    }

    private void initDeviceRecyclerView() {
        mDeviceRv = getView().findViewById(R.id.device_quick_control_recyclerview);
        mDeviceRv.setHasFixedSize(true); //设置固定大小
        //TODO 这里的间隔距离需要确定
        AverageGapItemDecoration itemDecoration =
                new AverageGapItemDecoration(60, 50, 0);
        mDeviceRv.addItemDecoration(itemDecoration);
        //创建线性布局
        mDeviceListAdapter = new DeviceRecyclerAdapter(R.layout.widget_device_inf_layout); //初始化适配器
        GridLayoutManager girdLayoutManager = new GridLayoutManager(getContext(), 2);
        mDeviceRv.setLayoutManager(girdLayoutManager);
        mDeviceRv.setAdapter(mDeviceListAdapter);
        mDeviceListAdapter.setEmptyView(R.layout.layout_empty);    //设置未发现设备时的布局
        mDeviceListAdapter.setOnItemClickListener(new OnItemClickListener() {  //卡片的点击事件
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                //卡片点击后进入设备详情dialog页面
                DeviceInfo deviceInfo = ((DeviceInfo) adapter.getItem(position));
                BaseDeviceInfo baseDeviceInfo = deviceInfo.getBaseDeviceInfo();
                if (baseDeviceInfo instanceof BulbInfo) {
//                    showBulbInfDialog(deviceInfo, (BaseQuickAdapter<DeviceInfo, ?>) adapter, position);
                } else if (baseDeviceInfo instanceof SocketInfo) {
                    //TODO 暂未写相关dialog代码
                } else if (baseDeviceInfo instanceof CurtainInfo) {
//                    showCurtainInfDialog(deviceInfo, (BaseQuickAdapter<DeviceInfo, ?>) adapter, position);
                }
            }
        });
    }

//    private void showBulbInfDialog(DeviceInfo deviceInfo, BaseQuickAdapter<DeviceInfo, ?> adapter, int position) {
//        mBulbControlDialog = new BulbControlDialog(getContext(), deviceInfo, adapter, position);
//        mBulbControlDialog.show();
//        bulbCancelBtn = mBulbControlDialog.getWindow().findViewById(R.id.bulb_cancel_btn);
//        bulbCancelBtn.setOnClickListener(this);
//
//    }
//
//    private void showCurtainInfDialog(DeviceInfo deviceInfo, BaseQuickAdapter<DeviceInfo, ?> adapter, int position) {
//        mCurtainControlDialog = new CurtainControlDialog(getContext(), deviceInfo, adapter, position);
//        mCurtainControlDialog.show();
//        curtainCancelBtn = mCurtainControlDialog.getWindow().findViewById(R.id.curtain_cancel_btn);
//        curtainCancelBtn.setOnClickListener(this);
//    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    public void onMessageEvent(MessageEvent event) {
        switch (event.getMessage()) {
            case FAMILY_CHANGE:
                mQuickPlaceAdapter.setSelection(0);
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bulb_cancel_btn:
                mBulbControlDialog.hide();
                break;
            case R.id.curtain_cancel_btn:
                mCurtainControlDialog.hide();
                break;
        }
    }
}
